#include "pluginssetting.h"
#include "ui_pluginssetting.h"
#include <QFileDialog>
#include <QPluginLoader>
#include <QComboBox>
#include <QMessageBox>
#include "MosaicPlugin/MosaicPlugin/PluginTemplate.h"
#include "mainwindowcrack.h"


PluginsSetting::PluginsSetting(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::PluginsSetting)
{
    QDir    pathProg(qApp->applicationDirPath());
    QString pathPlugs = pathProg.absoluteFilePath("plugins");

    ui->setupUi(this);
    this->move((parent->width() - this->width()) / 2, (parent->height() - this->height()) / 2);
    this->ui->txtPluginPath->setText(pathPlugs);
    this->fileSelected(pathPlugs);
}

PluginsSetting::~PluginsSetting()
{
    delete ui;
}

void PluginsSetting::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void PluginsSetting::fileSelected(const QString& file)
{
    QFileInfo   infoOnFile(file);
    QString     absolutePathFile;

    if (infoOnFile.isDir() == true) {
        QDir    pluginsDir(file);
        // effettua il caricamento dei plugins presenti nella directory:
        this->ui->cmbPlugins->clear();
        foreach (QString tmpFile, pluginsDir.entryList(QDir::Files)) {
            absolutePathFile = pluginsDir.absoluteFilePath(tmpFile);
            QPluginLoader loader(absolutePathFile);

            if (loader.load() == true) {
                PluginInterface *plugInfo = qobject_cast<PluginInterface *>(loader.instance());

                if (plugInfo)
                    this->ui->cmbPlugins->addItem(plugInfo->pluginDescription(), QVariant(absolutePathFile));
            }
        }        
        this->ui->txtPluginPath->setText(pluginsDir.path());
    }
}

void PluginsSetting::on_cmdClose_clicked()
{
    this->close();
}

void PluginsSetting::on_cmdSelectPath_clicked()
{
    QFileDialog *locatePlugins = new QFileDialog(this);

    locatePlugins->setFileMode(QFileDialog::Directory);
    locatePlugins->setOption(QFileDialog::ShowDirsOnly);
    locatePlugins->setDirectory(qApp->applicationDirPath());
    connect(locatePlugins, SIGNAL(fileSelected(QString)), this, SLOT(fileSelected(QString)));
    locatePlugins->show();
}


void PluginsSetting::on_cmdUsa_clicked()
{    
    MainWindowCrack *mainForm = qobject_cast<MainWindowCrack *>(this->parentWidget());

    if (this->ui->cmbPlugins->currentIndex() != -1) {
        mainForm->pluginLoader = new QPluginLoader(this->ui->cmbPlugins->itemData(this->ui->cmbPlugins->currentIndex()).toString(), mainForm);
        this->on_cmdClose_clicked();
    }
    else
        QMessageBox::warning(this, tr("Problema plugin"), tr("Selezionare un plugin valido dalla lista!"));
}
